<script setup lang="ts">
import { getCurrentInstance, ref, reactive, nextTick } from 'vue'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const picker = reactive({
  show: false,
  shade: false,
  box: false,
  // ---
  resInfo: [],
  // --mescroll--
  forScroll: null,
  info: {
    type: '',
    url: '',
    data: '',
    key: ['id', 'name']
  },
  page: { num: 0, size: 10 },
  noData: proxy.$Global.noData,
  items: [],
  // ----
  type: 1,
  button: [],
  filter: {
    show: false,
    msg: '',
    type: '',
    url: '',
    data: {},
    key: ''
  },
  // ----
  itemId: 0,
  infoSch: null,
  schKey: '',
  initPlace: '',
  // ----
  yes: '',
  no: ''
})

/* ---- */
const layer = ref()

/* ---- */
const open = (opt) => {
  if (opt) {
    for (const key in opt) { picker[key] = opt[key] }
  }
  picker.show = true
  nextTick(() => {
    picker.shade = true
    picker.box = true
    // ----
    setTimeout(() => { startMeScroll() }, 300)
  })
}
// --getData--
const startMeScroll = () => {
  picker.forScroll = new MeScroll(proxy.$refs.pickerScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: picker.page.num, size: picker.page.size },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.pickerList,
        tip: picker.noData
      }
    }
  })
}
const getListData = (page) => {
  const extra = {
    page: page.num,
    PageSize: page.size
  }
  if (picker.schKey) extra[picker.schKey] = picker.infoSch || undefined
  switch (String(picker.info.type)) {
    case 'post': {
      Object.assign(picker.info.data, extra)
      break
    }
    case 'get': {
      Object.assign(picker.info.data.params, extra)
      break
    }
  }
  // ----
  getListDataFromNet({
    forType: picker.info.type,
    forUrl: picker.info.url,
    forData: picker.info.data
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      picker.forScroll.endSuccess(curPageData ? curPageData.length : 0, true)
      picker.items = picker.items.concat(result)
    })
  }, (resMsg) => {
    picker.forScroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    picker.items = []
  }
  // ----
  proxy.$http[option.forType](option.forUrl, option.forData).then((res) => {
    switch (String(option.forType)) {
      case 'post': {
        if (res.success) {
          successCallback && successCallback(res.datainfo)
        } else { errorCallback && errorCallback(res.message) }
        break
      }
      case 'get': {
        successCallback && successCallback(res.items)
        break
      }
    }
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const getNeedDate = async (curItem) => {
  const extra = {}
  if (picker.filter.key) extra[picker.filter.key] = Number(curItem.value)
  switch (String(picker.filter.type)) {
    case 'post': {
      Object.assign(picker.filter.data, extra)
      break
    }
    case 'get': {
      Object.assign(picker.filter.data.params, extra)
      break
    }
  }
  // ----
  await proxy.$http[picker.filter.type](picker.filter.url, picker.filter.data).then((res) => {
    switch (String(picker.filter.type)) {
      case 'post': {
        if (res.success) curItem.show = false
        break
      }
      case 'get': {
        if (Number(res.items.length) > 0) curItem.show = false
        break
      }
    }
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    const curItem = {
      show: true,
      value: String(item[picker.info.key[0]]),
      text: proxy.$Myfun.setText(item[picker.info.key[1]])
    }
    // ----
    if (picker.filter.show) await getNeedDate(curItem)
    // ----
    newItems.push(curItem)
  }
  return newItems
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
  // ----
  getAuditFun(1)
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      // --重新请求数据--
      picker.forScroll.scrollTo(0)
      picker.forScroll.resetUpScroll()
      break
    }
    case 2: {
      if (!item.show) {
        proxy.$Myfun.forToast(layer.value, 'open', picker.filter.msg)
        return false
      }
      // ----
      picker.itemId = item ? item.value : 0
      picker.resInfo = item ? [item] : []
      break
    }
  }
}
// ----
const sureBtn = (index) => {
  if (picker.button.length > 1) {
    if (Number(index) === 0) {
      picker.no && picker.no()
    }else if (Number(index) === 3) {//新增按钮
      picker.add && picker.add()
    }  else {
      picker.yes && picker.yes(picker.resInfo)
    }
  }
  close()
}
const close = () => {
  picker.shade = false
  picker.box = false
  // ----
  setTimeout(() => {
    picker.show = false
    // ----
    picker.resInfo = []
    // --mescroll--
    picker.forScroll = null
    picker.info = {
      type: '',
      url: '',
      data: '',
      key: ['id', 'name']
    }
    picker.page = { num: 0, size: 10 }
    picker.noData = proxy.$Global.noData
    picker.items = []
    // ----
    picker.type = 1
    picker.button = []
    picker.itemId = 0
    // ----
    picker.infoSch = null
    picker.schKey = ''
    picker.initPlace = ''
    // ----
    picker.yes = ''
    picker.no = ''
  }, 300)
}
const maskClose = () => { close() }

/* ---- */
defineExpose({
  open
})
</script>

<template>
  <div class="pickerBox" v-if="picker.show">
    <transition name="fade">
      <div class="mask" v-if="picker.shade" @click="maskClose"></div>
    </transition>
    <transition name="slidDownUp" v-if="Number(picker.type) === 1">
      <div class="selbox" v-if="picker.box">
        <div class="SEB-btn xw-flex xw-flex-align xw-flex-justify">
          <template v-for="(item, index) in picker.button">
          <div class="SEB-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align" v-if="String(item) === 'forSch'">
            <em class="far fa-search"></em>
            <p class="xw-flex-W1"><input class="schText" type="text" :placeholder="picker.initPlace" v-model.trim="picker.infoSch" @blur="$Myfun.setIosToTop()"/></p>
            <transition name="fade"><em class="fa fa-times-circle SEB-L" @click="emptyInfo" v-if="picker.infoSch"></em></transition>
            <dfn class="SEB-sub xw-Lfg" @click="getAuditFun(1)">搜索</dfn>
          </div>
          <span :class="{'yes' : index > 0}" class="xw-radius-3 xw-act" @click="sureBtn(index)" v-else >{{item}}</span>
          </template>
        </div>
        <div class="SEB-body xw-flex">
          <div ref="pickerScroll" class="mescroll xw-flex-W1">
            <ul class="list-picker xw-flex xw-flex-column" ref="pickerList">
              <li class="xw-Tfg" v-for="(item, index) in picker.items" :class="{'active': Number(picker.itemId) === Number(item.value)}"><a class="xw-flex xw-flex-align" :class="{'xw-noData': !item.show}" @click="getAuditFun(2, item)">
                <em class="fal fa-check-circle"></em><div class="xw-ellipsis xw-flex-W1">{{item.text}}</div>
              </a></li>
            </ul>
          </div>
        </div>
      </div>
    </transition>
    <layer-view ref="layer"/>
  </div>
</template>

<style scoped>
/* ---- */
.pickerBox, .mask { position: fixed; z-index: 999; top: 0; left: 0; right: 0; bottom: 0; }
.mask { background: rgba(0, 0, 0, 0.5); }

/* ---- */
.selbox { position: fixed; left: 0; right: 0; bottom: 0; background: #eeeeee; -webkit-box-shadow: 0 0 1.4rem rgba(0, 0, 0, 0.4); box-shadow: 0 0 1.4rem rgba(0, 0, 0, 0.4); z-index: 999; }
.SEB-btn { padding: 0.8rem 0 0.8rem 1rem; }
.SEB-btn span { margin: 0 1rem 0 0; padding: 0.6rem 1.2rem; background: #ffffff; border: 1px solid #bbbbbb; }
.SEB-btn span.yes { background: #3388ff; border: 1px solid #3388ff; color: #ffffff; }
.SEB-sch { margin: 0 1rem 0 0; height: 3.4rem; border: 1px solid #cccccc; }
.SEB-sch em { padding: 0 1rem; font-size: 1.7rem; color: #bbbbbb; }
.SEB-sch p { padding: 0 1rem 0 0; }
.SEB-sub { padding: 0 1.2rem; font-size: 1.5rem; }
.SEB-sub:active { color: #3388ff; }
.SEB-L { margin-left: -1rem; }
.SEB-R { margin-right: -1rem; }
/* ---- */
.SEB-body { padding: 0 1rem; height: 40rem; }
.list-picker li:nth-of-type(1):before { display: none; }
.list-picker li a { height: 4rem ; font-size: 1.6rem; }
.list-picker li a em { margin-right: 1rem; color: #bbbbbb; }
.list-picker li.active a, .list-picker li.active a em { color: #ff5722; }
</style>
